"""
演示湖北省疫情地图开发
"""
import os
import json
from pyecharts.charts import Map
from pyecharts.options import TitleOpts, VisualMapOpts

current_path = os.getcwd()


def get_city_num(province_data):
    """
    根据各省的数据，将省份里面城市的名称和确诊人数以元组列表的方式返回
    :param province_data: 省份数据
    :return: 省内各城市的(市名, 确认人数)列表
    """
    list_data = []
    for temp in province_data:
        name = temp["name"]
        count = temp["total"]["confirm"]
        list_data.append((name, count))

    return list_data


def create_map_and_add_data(data, province):
    """
    创建地图对象并添加数据
    :param data: 地图内展示的数据（元组的列表）
    :param province: 需要展示的省份
    :return: 创建好的地图对象
    """
    map = Map()
    map.add(province + "省疫情地图", data, province)
    return map


def set_map_global_options(map, title):
    map.set_global_opts(
        title_opts=TitleOpts(title=title, pos_left="center", pos_bottom="1%"),
        visualmap_opts=VisualMapOpts(
            is_show=True,  # 是否显示
            is_piecewise=True,  # 是否分段
            pieces=[
                {"min": 1, "max": 99, "label": "1-99人", "color": "#CCFFFF"},
                {"min": 100, "max": 999, "label": "100-999人", "color": "#FFFF99"},
                {"min": 1000, "max": 4999, "label": "1000-4999人", "color": "#FF9966"},
                {"min": 5000, "max": 9999, "label": "5000-9999人", "color": "#FF6666"},
                {"min": 10000, "max": 49999, "label": "10000-49999人", "color": "#CC3333"},
                {"min": 50000, "label": "50000人以上", "color": "#990033"}
            ]
        )
    )
    return map


# 读取数据文件
try:
    f = open(current_path + "/疫情.txt", "r", encoding="UTF-8")
    json_str = f.read()
except Exception as e:
    print(f"读取数据出错：{e}，错误类型：{type(e)}")
else:
    f.close()

# 获取湖北省数据
data_dict = json.loads(json_str)
hubei_data_list = data_dict['areaTree'][0]['children'][6]["children"]
# 获取河南省数据
henan_data_list = data_dict['areaTree'][0]['children'][3]["children"]

# 准备数据为元组并放入list
map_hubei_data = get_city_num(hubei_data_list)
map_henan_data = get_city_num(henan_data_list)
# 构建地图
map_hubei = create_map_and_add_data(map_hubei_data, "湖北")
map_henan = create_map_and_add_data(map_henan_data, "河南")
# 设置全局选项
set_map_global_options(map_hubei, "湖北省疫情地图")
set_map_global_options(map_henan, "河南省疫情地图")
# 绘图
map_hubei.render("湖北省疫情地图.html")
map_henan.render("河南省疫情地图.html")
